package com.onLineCar.vehicle.config;


/**
 * 雪花算法工具类
 * @author Xinke_Li
 */
public class SnowflakeIdGenerator {
    // 起始的时间戳，可以根据自己的需求修改
    private final long START_TIMESTAMP = 1639257600000L; // 2021-12-12 00:00:00


    // 每个部分占用的位数
    private final long DATA_CENTER_ID_BITS = 5; // 数据中心ID所占位数
    private final long WORKER_ID_BITS = 5; // 工作机器ID所占位数
    private final long SEQUENCE_BITS = 12; // 序列号所占位数

    // 每个部分的最大值
    private final long MAX_DATA_CENTER_ID = ~(-1L << DATA_CENTER_ID_BITS);
    private final long MAX_WORKER_ID = ~(-1L << WORKER_ID_BITS);
    private final long MAX_SEQUENCE = ~(-1L << SEQUENCE_BITS);

    // 每个部分向左的位移
    private final long WORKER_ID_SHIFT = SEQUENCE_BITS;
    private final long DATA_CENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS;
    private final long TIMESTAMP_LEFT_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATA_CENTER_ID_BITS;

    private final long dataCenterId; // 数据中心ID
    private final long workerId; // 工作机器ID
    private long sequence = 0L; // 序列号
    private long lastTimestamp = -1L; // 上次生成ID的时间戳

    public SnowflakeIdGenerator(long dataCenterId, long workerId) {
        if (dataCenterId > MAX_DATA_CENTER_ID || dataCenterId < 0) {
            throw new IllegalArgumentException("Data center ID can't be greater than " + MAX_DATA_CENTER_ID + " or less than 0");
        }
        if (workerId > MAX_WORKER_ID || workerId < 0) {
            throw new IllegalArgumentException("Worker ID can't be greater than " + MAX_WORKER_ID + " or less than 0");
        }
        this.dataCenterId = dataCenterId;
        this.workerId = workerId;
    }

    public synchronized long nextId() {
        long timestamp = System.currentTimeMillis();

        if (timestamp < lastTimestamp) {
            throw new RuntimeException("Clock moved backwards. Refusing to generate ID");
        }

        if (timestamp == lastTimestamp) {
            sequence = (sequence + 1) & MAX_SEQUENCE;
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }

        lastTimestamp = timestamp;

        return ((timestamp - START_TIMESTAMP) << TIMESTAMP_LEFT_SHIFT)
                | (dataCenterId << DATA_CENTER_ID_SHIFT)
                | (workerId << WORKER_ID_SHIFT)
                | sequence;
    }

    protected long tilNextMillis(long lastTimestamp) {
        long timestamp = System.currentTimeMillis();
        while (timestamp <= lastTimestamp) {
            timestamp = System.currentTimeMillis();
        }
        return timestamp;
    }

    //public static void main(String[] args) {
    //    SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(1, 1);
    //
    //    // 生成10个订单编号示例
    //    for (int i = 0; i < 10; i++) {
    //        long orderId = idGenerator.nextId();
    //        System.out.println("订单编号: " + orderId);
    //    }
    //}
}
